<!--
  文件名: Blog.vue
  描述: 这是一个搜索部分，模糊搜索并显示搜索结果
  作者: 白紫铜
  创建日期: 2024-04-12
-->
<template>
  <div>
    <el-container>
      <el-aside style="width: 150px;"></el-aside>
      <el-main class="main">
        <el-row>
          <el-col :span="24" class="col_2">
            <el-tabs class="tabs_0" type="border-card">

              <el-tab-pane label="搜索结果" class="tab_pane">
                <div v-if="key_blogs.length === 0">
                  <el-empty description="什么都没有搜到"></el-empty>
                </div>
                <el-row v-for="blog in key_blogs" :key="blog.id">
                  <div class="blog-info">
                    <img :src="blog.coverUrl" alt="博客封面" style="display: flex; height: 135px;width: 240px;align-items: center;text-align: center">
                    <div class="blog-info-details">
                      <el-link @click="gotoBlogDetails(blog)" class="blog-info-title">{{ blog.title }}</el-link>
                      <div class="blog-info-description">{{ blog.summary }}</div>
                      <el-link class="blog-info-author" @click="gotoUserInfo(blog.author.username)" >作者：{{ blog.author.username }}</el-link>
                      <div class="blog-info-created-at">创建时间：{{ formatDate(blog.createdAt) }}</div>
                      <span class="blog-info-created-at">标签：{{ blog.tags }}</span>
                    </div>
                  </div>
                </el-row>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
        <div ref="loadMoreTrigger" style="height: 10px;"></div>
      </el-main>
      <el-aside style="width: 150px;"></el-aside>
    </el-container>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name:"SearchPosts",
  data(){
    return{
      username:"",
      blogs:[],
      page:0,
      tag_page:0,
      pageSize:10,
      loading:false,
      observer: null,
      key_blogs:[],
      keyword:"",
      isLogin:false,
    }
  },
  created() {
    const isAuthenticated=localStorage.getItem('token')
    this.$watch(
        () => this.$route.query.ts,
        () => {
          // 执行搜索操作
          this.searchPosts();
        }
    );
    if(isAuthenticated==null){
      this.isLogin=false
    }
    if(isAuthenticated){
      this.isLogin=true
    }
    this.keyword=decodeURIComponent(this.$route.params.keywords)
  },
  mounted() {
    this.observer=new IntersectionObserver(this.handleIntersection,{
      root:null,
      rootMargin:'0px',
      threshold:0.5,
    })
    this.observer.observe(this.$refs.loadMoreTrigger)
  },
  beforeUnmount() {
    if(this.observer){
      this.observer.disconnect()
    }
  },
  methods:{
    fetchBlogs(){
      const token=localStorage.getItem('token')
      const config={
        headers:{
          Authorization:`Bearer ${token}`
        },
        params:{
          page:this.page,
          pageSize:this.pageSize,
          keyword:this.keyword,
        }
      }
      axios.get('http://47.113.225.21:1145/key_blogs',config)
          .then(response=>{
            this.key_blogs=this.key_blogs.concat(response.data.content)
            this.page++
            this.loading=false
          }).catch(error => {
        console.error('获取博客数据失败', error);
        this.loading = false;
      });
    },
    formatDate(dateTime){
      const date=new Date(dateTime)
      const year=date.getFullYear()
      const month=String(date.getMonth()+1).padStart(2,'0')
      const day=String(date.getDay()).padStart(2,'0')
      return`${year}-${month}-${day}`;
    },
    handleIntersection(entries){
      entries.forEach(entry=>{
        if(entry.isIntersecting){
          this.fetchBlogs()
        }
      })
    },
    gotoBlogDetails(blog){
      this.$router.push({
            name:"BlogDetails",
            params:{
              user_id:blog.author.user_id,
              post_id:blog.id,
              title:encodeURIComponent(blog.title) // 编码标题，以防止特殊字符对路由造成影响
            }
          }
      )
    },
    gotoUserInfo(username){
      if(username==="账户已注销")
      {
        this.$message.info("用户已注销")
      }else {
        this.$router.push({name:"UserInfo",params:{user:encodeURIComponent(username)}})
      }
    },
    searchPosts() {
      if (this.keyword !== "") {
        // 检查当前搜索关键字是否与新的搜索关键字相同
        const currentKeyword = this.keyword;
        this.keyword = decodeURIComponent(this.$route.params.keywords); // 更新当前搜索关键字
        if (currentKeyword !== this.keyword) {
          // 重置组件数据状态
          this.key_blogs = []; // 清空之前的搜索结果
          this.page = 0; // 重置页数
          this.loading = true; // 开启加载状态

          const timestamp = new Date().getTime(); // 获取当前时间戳
          this.$router.replace({
            name: "SearchPosts",
            params: { keywords: encodeURIComponent(this.keyword) },
            query: { ts: timestamp } // 添加时间戳作为查询参数
          });

          // 重新加载搜索结果
          this.fetchBlogs();
        }
      } else {
        this.$message.error("搜索内容不能为空");
      }
    }


  }
}
</script>

<style scoped>
:deep(.el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active){
  color: #606266 !important;
  font-weight: bold;
}
:deep(.el-tabs--border-card>.el-tabs__header .el-tabs__item:not(.is-disabled):hover){
  color: #606266 !important;
  background-color: #ffffff;
}
.main{
  width: 1050px;
  min-height: calc(100vh - 65px);
  overflow-y: auto;
}
.blog-info {
  display: flex;
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  width: 100%;
}

.blog-info img {
  width: 160px;
  height: 90px;
  margin-right: 20px;
}

.blog-info-details {
  flex-grow: 1;
}

.blog-info-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.blog-info-author {
  font-style: italic;
  color: #666;
}

.blog-info-description {
  margin-top: 10px;
}
.el-link{
  color: black;
  text-decoration: none !important;
}
.el-link:hover{
  color: #606266;
  border-bottom: none !important;
  text-decoration: none !important;
}
.el-link::after{
  color: #606266;
  border-bottom: none !important;
  text-decoration: none !important;
}
</style>